<template>
	<el-dialog v-model="visible" :title="step == 1 ? '选择货品' : '编辑货品'" width="80%" :before-close="handleClose">
		<p class="mb16" v-if="step == 1">数据截止{{ dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss') }}</p>
		<ProTable
			:searchCol="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }"
			v-if="step == 1"
			ref="proTable"
			:columns="columns"
			:request-api="getTableList"
			:init-param="initParam"
			@current-change="handleCurrentChange"
			highlight-current-row
		>
			<template #expand="scope">
				{{ scope.row }}
			</template>
		</ProTable>
		<el-form span="1" ref="formRef" class="import-form" v-if="step == 2" :model="form" :rules="rules" label-width="100px" inline>
			<el-form-item label="物料编码" prop="materialCode">
				<el-input disabled v-model="form.materialCode" />
			</el-form-item>
			<el-form-item label="物料名称" prop="materialName">
				<el-input disabled v-model="form.materialName" :maxlength="30" />
			</el-form-item>
			<el-form-item label="生产年份" prop="productYear">
				<el-input disabled v-model="form.productYear" />
			</el-form-item>
			<el-form-item label="瓶储年份" prop="storeYear">
				<el-input disabled v-model="form.storeYear" />
			</el-form-item>
			<el-form-item label="售卖库存" prop="inventory">
				<div class="flex-center w-full">
					<el-input :disabled="!!row" class="flex-grow" v-model="form.inventory">
						<template #append> 件 </template>
					</el-input>
					<template v-if="props.row">
						<el-popover :visible="addVisible" placement="top-start" :width="200" trigger="click">
							<el-input v-model="count" placeholder="输入增加数量"></el-input>
							<div class="mt10 text-center">
								<el-button
									@click="
										count = '';
										addVisible = false;
									"
									size="small"
									>取消</el-button
								>
								<el-button type="primary" size="small" @click="changeCount('add')">确定</el-button>
							</div>
							<template #reference>
								<el-button
									type="primary"
									class="ml10"
									link
									@click="
										reduceVisible = false;
										addVisible = true;
									"
									>增加</el-button
								>
							</template>
						</el-popover>
						<el-divider direction="vertical" />
						<el-popover :visible="reduceVisible" placement="top-start" :width="200" trigger="click">
							<el-input v-model="count" placeholder="输入减少数量"></el-input>
							<div class="mt10 text-center">
								<el-button
									@click="
										count = '';
										reduceVisible = false;
									"
									size="small"
									>取消</el-button
								>
								<el-button type="primary" size="small" @click="changeCount('reduce')">确定</el-button>
							</div>
							<template #reference>
								<el-button
									type="primary"
									link
									@click="
										reduceVisible = true;
										addVisible = false;
									"
									>减少</el-button
								>
							</template>
						</el-popover>
					</template>
				</div>
			</el-form-item>
			<el-form-item class="flex">
				<el-form-item label="每件数量" prop="unitAmount" style="margin: 0 !important; width: calc(100% - 60px)">
					<el-input-number style="width: 100%" class="num-left" :controls="false" :min="0" :disabled="!!row" v-model="form.unitAmount">
					</el-input-number>
				</el-form-item>
				<el-form-item label="" label-width="0" prop="materialUnit" style="margin: 0 !important; width: 60px">
					<el-select :disabled="!!row" v-model="form.materialUnit">
						<el-option
							v-for="item in [
								{ label: '盒', value: 0 },
								{ label: '瓶', value: 1 },
							]"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
			</el-form-item>
			<el-form-item label="成本价" prop="costPrice">
				<el-input v-model="form.costPrice" />
			</el-form-item>
			<el-form-item label="建议售价" prop="recommendedPrice">
				<el-input v-model="form.recommendedPrice" />
			</el-form-item>
			<el-form-item label="所属品牌" prop="productBrandId">
				<RefreshSelect
					v-model="form.productBrandId"
					:api="fetchBrandList"
					:option-map="{ label: 'name', value: 'id' }"
					popper-class="refresh-select"
					link="/goods/brand"
				>
				</RefreshSelect>
			</el-form-item>
			<el-form-item label="香型" prop="flavor">
				<el-input v-model="form.flavor" />
			</el-form-item>
			<el-form-item label="酒精度" prop="alcohol">
				<el-input v-model="form.alcohol" />
			</el-form-item>
			<el-form-item label="净含量" prop="net">
				<el-input v-model="form.net" />
			</el-form-item>
			<el-form-item label="产地" prop="area">
				<el-input v-model="form.area" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button v-if="step == 1" @click="handleClose">取消</el-button>
				<el-button type="primary" v-if="step == 1" :disabled="!form" @click="toNext">下一步</el-button>
				<el-button v-if="step == 2 && !props.row" type="primary" @click="onPrev">上一步</el-button>
				<el-button type="primary" v-if="step == 2" v-debounce="onSubmit">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="tsx">
import { FormRules, ElMessage } from 'element-plus';
import { ref, reactive, watch, computed, nextTick, onMounted } from 'vue';
import {
	fetchWarehousingGoods,
	fetchImportWarehousing,
	fetchWarehouseDetail,
	fetchUpdateWarehousing,
	fetchBrandList,
	fetchProductLargeType,
} from '/@/api/goods';
import ProTable from '../../../../../components/ProTable/index.vue';
import RefreshSelect from '/@/components/refreshSelect/index.vue';

import { ProTableInstance, ColumnProps } from '../../../../../components/ProTable/interface';
import dayjs from 'dayjs';
import { fenToYuan } from '/@/utils/commonFunction';

const props = defineProps({
	// 列表内容
	visible: {
		type: Boolean,
		default: () => false,
	},
	row: {
		type: Object,
		default: () => null,
	},
});

const emit = defineEmits(['handleClose']);

watch(
	() => props.visible,
	async (val: any) => {
		if (props.row) {
			const res = await fetchWarehouseDetail({ id: props.row.id });
			const storeYear = dayjs().diff(res.data.productYear, 'year') - 1;
			form.value = {
				...res.data,
				costPrice: fenToYuan(res.data.costPrice),
				recommendedPrice: fenToYuan(res.data.recommendedPrice),
				storeYear: storeYear < 0 ? 0 : storeYear,
			};
			step.value = 2;
		} else {
			step.value = 1;
		}
		visible.value = val;
	}
);

const step = ref(1);

const count = ref();

const addVisible = ref(false);
const reduceVisible = ref(false);

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'materialCode',
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
	};
	if (data.paramValue) {
		data[data.paramCode] = data.paramValue;
	}
	delete data.paramValue;
	delete data.paramCode;

	return fetchWarehousingGoods(data);
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '物料搜索',
		isShow: false,
		search: {
			span: 3,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 3,
			xl: 3,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.paramCode = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'identifier',
		label: '',
		minWidth: 50,
		render: (scope) => {
			return (
				<el-radio-group v-model={form.value.identifier}>
					<el-radio value={scope.row.identifier}></el-radio>
				</el-radio-group>
			);
		},
	},
	{
		prop: 'materialName',
		label: '物料名称',
		minWidth: 120,
	},
	{
		prop: 'materialCode',
		label: '物料编码',
		minWidth: 120,
	},
	{
		prop: 'type',
		label: '产品大类',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '选择产品大类', clearable: true, filterable: true } },
		render: (scope) => {
			return scope.row.type;
		},
		enum: () => {
			return new Promise<any>((resolve) => {
				fetchProductLargeType().then((res: any) => {
					resolve({
						code: 200,
						msg: 'success',
						data: res.data.map((v: any) => ({ label: v, value: v })),
					});
				});
			});
		},
	},
	{
		prop: 'core',
		label: '是否核心大单品',
		minWidth: 140,
		search: { el: 'select', props: { placeholder: '选择是否核心大单品', clearable: true, filterable: true } },
		enum: [
			{
				label: '是',
				value: 1,
			},
			{
				label: '否',
				value: 0,
			},
		],
	},
	{
		prop: 'totalInventory',
		label: '在库总库存数量',
		minWidth: 140,
	},
	{
		prop: 'freeInventory',
		label: '非限制性库存数量',
		minWidth: 160,
	},
	{
		prop: 'frozenInventory',
		label: '冻结库存数量',
		minWidth: 140,
	},
	// {
	// 	prop: 'brandName',
	// 	label: '所属品牌',
	// 	minWidth: 120,
	// },
	{
		prop: 'productYear',
		label: '生产年份',
		minWidth: 120,
	},
];

const searchArr = [
	{
		label: '物料编码',
		value: 'materialCode',
	},
	{
		label: '物料名称',
		value: 'materialName',
	},
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const loading = ref(false);
const visible = ref(false);
const formRef = ref();
const form = ref<any>({
	materialUnit: 1,
});

//校验规则
const rules = reactive<FormRules<any>>({
	materialCode: [{ required: true, trigger: 'blur', message: '物料编码不能为空' }],
	materialName: [{ required: true, trigger: 'blur', message: '物料名称不能为空' }],
	productYear: [{ required: true, trigger: 'blur', message: '生产年份不能为空' }],
	storeYear: [{ required: true, trigger: 'blur', message: '瓶储年份不能为空' }],
	inventory: [{ required: true, trigger: 'blur', message: '售卖库存不能为空' }],
	unitAmount: [{ required: true, trigger: 'blur', message: '每件数量不能为空' }],
	materialUnit: [{ required: true, trigger: 'blur', message: '每件数量不能为空' }],
	recommendedPrice: [{ required: true, trigger: 'blur', message: '建议售价不能为空' }],
	costPrice: [{ required: true, trigger: 'blur', message: '成本价不能为空' }],
	productBrandId: [{ required: true, trigger: 'blur', message: '所属品牌不能为空' }],
	flavor: [{ required: true, trigger: 'blur', message: '香型不能为空' }],
	alcohol: [{ required: true, trigger: 'blur', message: '酒精度不能为空' }],
	net: [{ required: true, trigger: 'blur', message: '净含量不能为空' }],
	area: [{ required: true, trigger: 'blur', message: '产地不能为空' }],
});

const handleCurrentChange = (val: any) => {
	const storeYear = dayjs().diff(val.productYear, 'year') - 1;
	form.value = {
		...val,
		storeYear: storeYear < 0 ? 0 : storeYear,
		flavor: '浓香型',
		alcohol: val.materialName.slice(0, 2) + '%vol.',
		area: '四川 泸州',
		materialUnit: 1,
	};
};

const changeCount = (type: string) => {
	if (type == 'add') {
		form.value.inventory = Number(form.value.inventory) + Number(count.value);
	} else {
		form.value.inventory = Number(form.value.inventory) - Number(count.value);
	}
	count.value = '';
	addVisible.value = false;
	reduceVisible.value = false;
};

const toNext = () => {
	if (!form.value.materialCode) {
		ElMessage.error('请选择货品');
		return;
	}
	step.value = 2;
};
const onPrev = () => {
	step.value = 1;
	nextTick(() => {
		proTable.value!.setCurrentRow(form.value);
	});
};

const onSubmit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params = { ...form.value };
			(params.recommendedPrice = form.value.recommendedPrice * 100), (params.costPrice = form.value.costPrice * 100);

			const res = props.row ? await fetchUpdateWarehousing(params) : await fetchImportWarehousing(params);
			if (res.code == 200) {
				ElMessage.success(props.row ? '编辑货品成功' : '导入货品成功');
				handleClose(true);
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const handleClose = (success: boolean) => {
	form.value = {};
	if (formRef.value) {
		formRef.value.resetFields();
	}
	emit('handleClose', success === true);
};
</script>

<style lang="scss">
.import-form {
	.el-form-item {
		width: 44%;
	}
}
</style>
